﻿using System;
using System.Data;
using System.Reflection;
using System.Windows.Forms;
using AbpCodeBuilder.CodeHelper;
using DevExpress.XtraBars;
using DevExpress.XtraTreeList.Nodes;

namespace AbpCodeBulider.DxUI
{
    internal partial class FrmMain : DevExpress.XtraEditors.XtraForm
    {
       

        public FrmMain()
        {
            InitializeComponent();
            LookAndFeel.SetSkinStyle(strSkin);
        }
        internal Action lastAction = null;
        internal Action refreshAction = null;
        internal DataTable DtDbName = new DataTable();
        internal DataTable DtNames = new DataTable();
        internal string DBName = string.Empty;
        internal string DataTableName = string.Empty;
        internal string DataTableId = string.Empty;
        internal string Xtype = "U";
        public static string strSkin = "Office 2010 Blue";
        private bool tlFlag = false;


        #region 窗体初始化

        private void frmMain_Load(object sender, EventArgs e)
        {
            //recModel.AddService(typeof (ISyntaxHighlightService), new SyntaxHighlightService(recModel));

            BindStyle();

            this.WindowState = FormWindowState.Maximized;

            this.tlData.TreeLevelWidth = 8;

            FrmCode doc = new FrmCode();
            doc.FrmMain = this;
            doc.MdiParent = this;

            doc.Show();
            for (int i = 0; i < documentManager1.View.Documents.Count; i++)
            {
                if (this.documentManager1.View.Documents[i].Form.Name == "FrmCode")
                {
                    this.documentManager1.View.Documents[i].Properties.AllowClose =
                        DevExpress.Utils.DefaultBoolean.False;
                }
            }
        }

        #endregion

        #region 连接数据库
        private void btnConncetion_Click(object sender, EventArgs e)
        {
            FrmConnection fc = new FrmConnection();
            fc.LookAndFeel.SetSkinStyle(this.LookAndFeel.SkinName);
            fc.ConnectionDelegate += GetDatabases;
            fc.ShowDialog();

            ////1.获取所有数据库
            //GetDatabases();
        }

        private void GetDatabases()
        {
            DtDbName = SqlHelper.Query("select * from sysdatabases where dbid>4 order by name");
            tlData.Nodes.Clear();
            this.tlData.BeginUnboundLoad();
            TreeListNode rootNode = this.tlData.AppendNode(new object[] {"数据库", -1}, null);

            for (int i = 0; i < DtDbName.Rows.Count; i++)
            {
                TreeListNode tlnDb =
                    this.tlData.AppendNode(new object[] {DtDbName.Rows[i]["name"], DtDbName.Rows[i]["dbid"]}, rootNode);
                //数据库节点

                tlnDb.TreeList.AppendNode(new object[] {"表"}, tlnDb); //表节点
                tlnDb.TreeList.AppendNode(new object[] {"视图"}, tlnDb);
                tlnDb.TreeList.AppendNode(new object[] {"存储过程"}, tlnDb);
            }

            this.tlData.EndUnboundLoad();

            rootNode.Expanded = true;
        }

        #endregion

        #region 当树获取焦点时
        private void tlData_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {

            try
            {
                WaitForm.ShowWaitForm();
                int level = this.tlData.FocusedNode.Level;
                string name = e.Node.GetValue("name").ToString(); //获取数据库名或表名
                string tableName = null;

                e.Node.Expanded = !tlFlag;

                if (level == 1)
                {
                    lblDbText.Text = name;
                    DBName = name;
                }

                if (level == 3)
                {
                    tableName = e.Node.ParentNode.ParentNode.GetValue("name").ToString(); //获取数据库名
                    DBName = tableName;
                    lblDtText.Text = name;
                    DataTableName = name;
                    DataTableId = e.Node.GetValue("id").ToString(); //获取表的Id
                    string strName = null;
                    strName = tlData.FocusedNode.ParentNode.GetValue("name").ToString();
                    if (strName == "表")
                    {
                        Xtype = "U";
                    }
                    else if (strName == "视图")
                    {
                        Xtype = "V";
                    }
                    if (refreshAction != null)
                    {
                        refreshAction();
                    }
                }
            }
            finally
            {
                WaitForm.CloseWaitForm();
            }
        }
        private void tlData_DoubleClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(DBName))
            {
                MessageBox.Show("请选择一个数据库");
                return;
            }
            if (string.IsNullOrEmpty(DataTableId))
            {
                MessageBox.Show("请选择一个表");
                return;
            }



        }
        #endregion

        #region 当节点展开时
        private void tlData_AfterExpand(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            try
            {
                WaitForm.ShowWaitForm();
                int level = e.Node.Level;//获取数据库下的子节点级别

                if (level != 1) return;
                e.Node.Selected = true;
                string dbName = e.Node.GetValue("name").ToString();//获取数据库名

                lblDbText.Text = dbName;
                DBName = dbName;

                DataTable dtName = SqlHelper.Query("select name,id from sysobjects where xtype='U' order by name ", dbName);//获取选中数据库的表名
                DtNames = dtName;

                DataTable dtView = SqlHelper.Query("select name,id from sysobjects where type='V' order by name", dbName);//获取选中数据库的视图

                DataTable dtProc = SqlHelper.Query("select name,object_id from sys.objects where type='p' order by name", dbName);
                //清除已存在的节点
                if (e.Node.Nodes[0].Nodes.Count > 0)
                    e.Node.Nodes[0].Nodes.Clear();

                if (e.Node.Nodes[1].Nodes.Count > 0)
                    e.Node.Nodes[1].Nodes.Clear();

                if (e.Node.Nodes[2].Nodes.Count > 0)
                    e.Node.Nodes[2].Nodes.Clear();

                //添加到表的节点
                for (int i = 0; i < dtName.Rows.Count; i++)
                {
                    if (e.Node.Nodes.Count > 0)
                        this.tlData.AppendNode(new object[] { dtName.Rows[i]["name"], dtName.Rows[i]["id"] }, e.Node.Nodes[0]);
                }

                //添加到视图的节点
                for (int i = 0; i < dtView.Rows.Count; i++)
                {
                    //this.tlData.Nodes.Clear();
                    this.tlData.AppendNode(new object[] { dtView.Rows[i]["name"], dtView.Rows[i]["id"] }, e.Node.Nodes[1]);
                }

                for (int i = 0; i < dtProc.Rows.Count; i++)
                {
                    //this.tlData.Nodes.Clear();
                    this.tlData.AppendNode(new object[] { dtProc.Rows[i]["name"], dtProc.Rows[i]["object_id"] },
                                           e.Node.Nodes[2]);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("没有该数据库的访问权限");
            }
            finally
            {
                WaitForm.CloseWaitForm();
            }

        } 
        #endregion
        
        #region 获取皮肤样式
        public  void BindStyle()
        {
            int itemId = 0;
            foreach (DevExpress.Skins.SkinContainer skinContainer in DevExpress.Skins.SkinManager.Default.Skins)
            {
                BarButtonItem sBtnItem = new BarButtonItem();
                sBtnItem.Id = itemId;
                sBtnItem.Name = "bItem" + itemId.ToString();
                sBtnItem.Caption = skinContainer.SkinName;
                sBtnItem.ItemClick += new ItemClickEventHandler(sBtnItem_ItemClick);
                sBtnItem.ButtonStyle = BarButtonStyle.Check;
                sBtnItem.GroupIndex = 1;

                if (skinContainer.SkinName == "Office 2010 Blue")
                {
                    this.LookAndFeel.SetSkinStyle(skinContainer.SkinName);
                    sBtnItem.Down = true;
                }

                bsiSkins.AddItem(sBtnItem);

            }
        }

        void sBtnItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.LookAndFeel.SetSkinStyle(e.Item.Caption);
            strSkin = e.Item.Caption;
        }

        #endregion

        #region 创建窗口
        /// <summary>
        /// 创建窗口
        /// </summary>
        /// <param name="type">窗口类型</param>
        /// <param name="isShowDialog"></param>
        internal void CreateForm(Type type, bool isShowDialog = false)
        {
            FrmBase f = CheckOpen(type.Name);
            if (f != null)
            {
                f.Activate();
                return;
            }
            FrmBase doc = (FrmBase)(Assembly.GetAssembly(type).CreateInstance(type.FullName));
            doc.strName = type.Name;
            doc.FrmMain = this;
            if (isShowDialog)
            {
                doc.ShowDialog();
            }
            else
            {
                doc.MdiParent = this;
                doc.Show();
            }
        } 
        #endregion

        /// <summary>
        /// 检查窗口是否已经打开
        /// </summary>
        /// <param name="frmName">窗口标识</param>
        /// <returns></returns>
        internal FrmBase CheckOpen(string frmName)
        {
            foreach (Form frm in this.MdiChildren)
            {
                try
                {
                    FrmBase f = (FrmBase)frm;
                    if (f != null)
                    {
                        if (f.strName == frmName)
                        {
                            return f;
                        }
                    }
                }
                catch
                {
                }
            }
            return null;
        }


        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }






       
    }
}
